const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

// ArrayBuffer转为字符串，参数为ArrayBuffer对象
const ab2str = function (buf) {
  return String.fromCharCode.apply(null, new Uint8Array(buf));
}

// ArrayBuffer转为字符串，参数为ArrayBuffer对象
const ab2strU16 = function (buf) {
  return String.fromCharCode.apply(null, new Uint16Array(buf));
}

// 字符串转为ArrayBuffer对象，参数为字符串
const str2ab = function(str) {
  var buf = new ArrayBuffer(str.length * 2); // 每个字符占用2个字节
  var bufView = new Uint16Array(buf);
  for (var i = 0, strLen = str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}

/**
 * 十六进制转 bytearray
 */
var hex2ab = function(hex){
  var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {
    return parseInt(h, 16)
  }))

  var buffer = typedArray.buffer
  return buffer
}

 // ArrayBuffer转16进度字符串示例
const ab2hex = function (buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}

const intTo2Hex = function(value){

  value = parseInt(value)
  if (!isNaN(value)){
    let hex = value.toString(16);
    if(hex.length == 1){
      hex =  "0" + hex;
    }

    return hex;
  }

  console.log("value is null or ''")
}

/**
 * 转4个字符
 */
const intTo4Hex = function (value) {
  value = parseInt(value)
  if (!isNaN(value)) {
    let hex = value.toString(16);
    while(hex.length < 4){
      hex = "0" + hex;
    }

    return hex;
  }

  console.log("value is null or ''")
}

module.exports = {
  formatTime: formatTime,
  ab2str: ab2str,
  str2ab: str2ab,
  ab2hex: ab2hex,
  hex2ab: hex2ab,
  intTo2Hex: intTo2Hex,
  intTo4Hex: intTo4Hex
}
